package com.driving.single.intercepter;

import com.driving.single.common.entity.DrivingResult;
import com.driving.single.common.entity.LoginResult;
import com.driving.single.common.utils.JsonUtils;
import com.driving.single.intercepter.service.UserLoginCheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 用户登录拦截器
 */
@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserLoginCheckService userLoginCheckService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter("token");
        String uid = request.getParameter("uid");
        String resultMsg = null;
        if (!StringUtils.isEmpty(token) && !StringUtils.isEmpty(uid)) {
            // 如果用户 token 不为空，则校验用户在 redis 中是否失效
            LoginResult loginResult = this.userLoginCheckService.checkUserToken(token, uid);
            if (loginResult != null) {
                return true;
            } else {
                resultMsg = "登录已过期，请重新登录！";
            }
        }
        // 401 需要登录或者说没有通过认证
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        DrivingResult drivingResult = new DrivingResult();
        drivingResult.setStatus(401);
        if(resultMsg == null){
            resultMsg = "未登录，请前往登录页面！";
        }
        drivingResult.setMsg(resultMsg);
        response.getWriter().write(Objects.requireNonNull(JsonUtils.objectToJson(drivingResult)));
        return false;
    }
}
